﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters;
using System.Web.Security;
using System.Net.Http;
using System.Collections.ObjectModel;
using System.Net.Http.Headers;
using System.Threading;
using System.Security.Principal;
using System.Net;
using System.Text;
using XQ.RequestOfficeSupplies.WebAPI.Common;
using XQ.RequestOfficeSupplies.DAL.Model;
using XQ.RequestOfficeSupplies.DAL.Models;
using XQ.RequestOfficeSupplies.DAL.DAL.Common;

namespace XQ.RequestOfficeSupplies.WebAPI.Filter
{
    /// <summary>
    /// FORM身份验证
    /// </summary>
    public class FormAuthenticationFilterAttribute: AuthorizationFilterAttribute
    {
        private const string UnauthorizedMessage = "请求未授权，拒绝访问。";
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            LogHelper.WriteLog("开始验证权限！");
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0)
            {
                base.OnAuthorization(actionContext);
                return;
            }

            var authorization = actionContext.Request.Headers.Authorization;
            if (authorization != null)
            {
                try
                {
                    //LogHelper.WriteLog(authorization.Scheme);
                    //LogHelper.WriteLog(authorization.Parameter);
                    if (authorization.Scheme == "Bearer")
                    {
                        string tokenStr = authorization.Parameter;
                        TokenModel token = TokenHelper.DecryptToken(tokenStr);
                        //Token超时
                        if (token.Timeout < DateTime.Now.Ticks)
                        {
                            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("无授权", Encoding.UTF8) };
                            return;
                        }
                    }
                    else
                    {
                        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("无授权", Encoding.UTF8) };
                    }
                }
                catch (Exception ex)
                {
                    //LogHelper.WriteLog("验证权限时报错", ex);
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent(ex.Message, Encoding.UTF8) };
                    return;
                }
            }
            else
            {
                LogHelper.WriteLog("没有读取到Authorization");
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("无授权", Encoding.UTF8) };
            }


            base.OnAuthorization(actionContext);
        }

    }
}